<template>
  <el-dialog title="数据导入" :visible.sync="show" width="40%" :close-on-click-modal="false" center>
    <el-upload
        ref="uploader"
        multiple
        accept=".xlsx,.xls"
        :limit="limit"
        :action="action"
        :http-request="importExcelHandler"
        :before-upload="beforeUploadHandler"
        :on-success="successHandler"
        :on-remove="removeHandler"
        :on-exceed="exceedHandler"
        :file-list="fileList"
        :auto-upload="false"
        :on-error="errorHandler"
        :on-change="fileChangeHandler"
    >
      <el-button slot="trigger" icon="el-icon-folder-add" size="small" type="primary">选择文件</el-button>
      <el-button style="margin-left: 10px;" size="small" icon="el-icon-upload" type="success" :disabled="impBtnDisabled"
                 @click="dataImportHandler" :loading="importBtnLoading">{{ importBtnText }}
      </el-button>
      <a style="margin-left: 10px" v-if="downLoadTemplateUrl?true:false"
         :href="downLoadTemplateUrl">下载模版</a>
      <div slot="tip" class="el-upload__tip">只能上传{{ limit }}个xlsx/xls文件，单个文件不超过20MB</div>
      <div slot="tip" style="color: red;margin-top: 20px">{{ errorMessage }}</div>
    </el-upload>
  </el-dialog>
</template>

<script>
import * as tools from '@/utils/tools'
import ajax from "@/utils/ajax";

export default {
  props: {
    uploadUrl: {
      type: String,
      default: ""
    },

    downLoadTemplateUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      errorMessage: '',
      show: false,
      importBtnLoading: false,
      importBtnText: "开始导入",
      limit: 1,
      visible: false,
      impBtnDisabled: true,
      fileList: [],
      action: '',
      params: new FormData()
    }
  },
  methods: {
    showImport() {
      this.clearUploadParams()
      this.importBtnLoading = false
      this.importBtnText = "开始导入"
      this.impBtnDisabled = true
      this.fileList = []
      this.show = true
    },
    closeImport() {
      this.show = false
    },
    changeErrorMessage(error) {
      this.errorMessage = error
    },
    beginImport() {
      this.importBtnText = "导入中，请稍等"
      this.importBtnLoading = true
      this.errorMessage = ""
    },
    endImport() {
      this.importBtnText = "开始导入"
      this.importBtnLoading = false
    },

    errorHandler(res, file, fileList) {
      this.endImport()
      this.$emit("on-importFail", res)
    },
    successHandler(res, file, fileList) {
      this.endImport()
      this.$emit("on-importSuccess", res)
    },
    removeHandler(file, fileList) {
      this.impBtnDisabled = true
    },
    fileChangeHandler(file, fileList) {
      this.impBtnDisabled = false
    },
    addUploadParams(key, value) {
      this.params.append(key, value)
    },
    clearUploadParams() {
      this.params = new FormData()
    },
    importExcelHandler(option) {
      this.params.append("file", option.file)
      this.beginImport()
      ajax.uploadPost(this.uploadUrl, this.params).then(res => {
        this.successHandler(res)
      }).catch(resp => {
        option.onError(resp)
      })
    },
    dataImportHandler() {
      this.$refs.uploader.submit();
    },
    beforeUploadHandler(file) {
      let fileType = file.name.split(".")[1]
      const isXlsxAndXls = ["xlsx", "xls"].some(type => {
        return fileType === type
      })
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isXlsxAndXls) {
        this.$message.error('上传文件只能是 xlsx/xls 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return false
      }
      return true
    },

    exceedHandler(files, fileList) {
      tools.notify({
        type: 'error',
        message: `当前限制选择 ` + this.limit + ` 个文件`
      })
    }
  }
}
</script>
